package com.atguigu.qqzone.service.impl;

import com.atguigu.qqzone.dao.HostReplyDAO;
import com.atguigu.qqzone.dao.ReplyDAO;
import com.atguigu.qqzone.pojo.HostReply;
import com.atguigu.qqzone.pojo.Reply;
import com.atguigu.qqzone.pojo.Topic;
import com.atguigu.qqzone.pojo.UserBasic;
import com.atguigu.qqzone.service.ReplyService;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ReplyServiceImpl
 * @Description:
 * @Author: wty
 * @Date: 2022/12/9
 */

public class ReplyServiceImpl implements ReplyService {
    private ReplyDAO replyDAO;
    /**
     * 调用hostReplyServiceImpl的实现
     */
    private HostReplyServiceImpl hostReplyServiceImpl;
    private UserBasicServiceImpl userBasicServiceImpl;

    @Override
    public List<Reply> getReplyListByTopicId(Integer topicId) {
        String sqlStr = "SELECT a.* FROM qqzonedb2.`t_reply` a,qqzonedb2.`t_topic` b,qqzonedb2.`t_user_basic` c WHERE a.`topic` = b.`id`  AND a.`author` = c.`id` AND a.`topic` = ?";
        ArrayList<Reply> list = new ArrayList<>();

        List<Reply> replyList = replyDAO.queryMultiListAndMapReply(sqlStr, list, topicId);
        for (int i = 0; i < replyList.size(); i++) {
            Reply reply = replyList.get(i);
            // 1.将关联的作者设置进去
            UserBasic author = userBasicServiceImpl.getUserBasicById(reply.getAuthor().getId());
            reply.setAuthor(author);

            // 2.将关联的hostReplyByReplyId设置
            HostReply hostReplyByReplyId = hostReplyServiceImpl.getHostReplyByReplyId(reply.getId());
            reply.setHostReply(hostReplyByReplyId);
        }
        return replyList;
    }

    @Override
    public void addReply(Reply reply) {
        String sqlStr = "INSERT INTO qqzonedb2.`t_reply` VALUES(0,?,?,?,?)";
        replyDAO.dml(sqlStr, reply.getContent(), reply.getReplyDate(), reply.getAuthor().getId(), reply.getTopic().getId());
    }

    @Override
    public void delReply(Integer id) {
        String sqlStr = "";
        // 1.根据id获取到reply
        Reply reply = getReply(id);
        // 2.如果reply有关联的hostreply那么需要删除hostreply
        if (null != reply) {
            HostReply hostReply = hostReplyServiceImpl.getHostReplyByReplyId(reply.getId());
            if (null != hostReply) {
                hostReplyServiceImpl.delHostReply(hostReply.getId());
            }
            // 3.最后再删除reply
            sqlStr = "DELETE FROM qqzonedb2.`t_reply` WHERE id = ?";
            replyDAO.dml(sqlStr, id);
        }
    }

    @Override
    public Reply getReply(Integer id) {
        String sqlStr = "SELECT a.* FROM qqzonedb2.`t_reply` a WHERE a.id = ?";
        return replyDAO.querySingleReply(sqlStr, id);
    }

    @Override
    public void delReplyList(Topic topic) {
        List<Reply> replyList = getReplyListByTopicId(topic.getId());
        if (null != replyList) {
            for (Reply reply : replyList) {
                delReply(reply.getId());
            }
        }
    }
}
